<template>
  <ElDialog
    :model-value="visible"
    :title="dialogTitle"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleCancel"
  >
    <div class="merchant-dialog-content">
      <ElForm
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
        class="merchant-form"
        label-position="right"
      >
        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElFormItem label="商户编号" prop="merchantCode">
              <ElInput
                v-model="formData.merchantCode"
                placeholder="请输入商户编号"
                clearable
                :disabled="isEdit"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="商户名称" prop="merchantName">
              <ElInput
                v-model="formData.merchantName"
                placeholder="请输入商户名称"
                clearable
              />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElFormItem label="企业类型" prop="merchantType">
              <ElSelect
                v-model="formData.merchantType"
                placeholder="请选择企业类型"
                class="w-full"
              >
                <ElOption
                  v-for="type in merchantTypeOptions"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value"
                />
              </ElSelect>
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="商户级别" prop="merchantLevel">
              <ElInput
                v-model="formData.merchantLevel"
                placeholder="请输入商户级别"
                clearable
              />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElFormItem label="开户银行" prop="bankName">
              <ElInput
                v-model="formData.bankName"
                placeholder="请输入开户银行"
                clearable
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="银行账户" prop="bankAccount">
              <ElInput
                v-model="formData.bankAccount"
                placeholder="请输入银行账户"
                clearable
              />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElFormItem label="联系地址" prop="address">
          <ElInput
            v-model="formData.address"
            placeholder="请输入联系地址"
            clearable
          />
        </ElFormItem>

        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElFormItem label="手机号码" prop="mobile">
              <ElInput
                v-model="formData.mobile"
                placeholder="请输入手机号码"
                clearable
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="座机号码" prop="tel">
              <ElInput
                v-model="formData.tel"
                placeholder="请输入座机号码"
                clearable
              />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElFormItem label="联系人" prop="contactPerson">
              <ElInput
                v-model="formData.contactPerson"
                placeholder="请输入联系人"
                clearable
              />
            </ElFormItem>
          </ElCol>
          <ElCol :span="12">
            <ElFormItem label="邮箱地址" prop="email">
              <ElInput
                v-model="formData.email"
                placeholder="请输入邮箱地址"
                clearable
                type="email"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>

        <ElFormItem label="备注信息" prop="remark">
          <ElInput
            v-model="formData.remark"
            placeholder="请输入备注信息"
            type="textarea"
            :rows="3"
            clearable
          />
        </ElFormItem>
      </ElForm>
    </div>

    <template #footer>
      <div class="dialog-footer flex gap-3 justify-end">
        <ElButton @click="handleCancel">取消</ElButton>
        <ElButton
          type="primary"
          :loading="submitting"
          @click="handleConfirm"
        >
          确定
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
/**
 * 商户信息对话框组件
 * 参照原项目 RuoYi-WMS-VUE/src/views/wms/basic/merchant/index.vue 的抽屉表单逻辑
 * 用 art-design-pro 风格重新实现
 */
import { ref, reactive, computed, watch, nextTick } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";

/** 商户类型选项 */
const merchantTypeOptions = [
  { label: "生产企业", value: "1" },
  { label: "贸易企业", value: "2" },
  { label: "物流企业", value: "3" },
  { label: "电商企业", value: "4" },
  { label: "其他", value: "9" },
];

/** 商户数据接口 */
interface MerchantData {
  id?: number;
  merchantCode: string;
  merchantName: string;
  merchantType: string;
  merchantLevel?: string;
  bankName?: string;
  bankAccount?: string;
  address?: string;
  mobile?: string;
  tel?: string;
  contactPerson?: string;
  email?: string;
  remark?: string;
}

/** Props */
interface Props {
  visible: boolean;
  data?: Partial<MerchantData>;
  mode?: "add" | "edit";
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  data: undefined,
  mode: "add",
});

/** Emits */
interface Emits {
  (event: "update:visible", visible: boolean): void;
  (event: "confirm", data: MerchantData): void;
  (event: "cancel"): void;
}

const emit = defineEmits<Emits>();

/** 响应式数据 */
const formRef = ref<FormInstance>();
const submitting = ref(false);

/** 是否编辑模式 */
const isEdit = computed(() => props.mode === "edit");

/** 对话框标题 */
const dialogTitle = computed(() => (isEdit.value ? "编辑商户" : "新增商户"));

/** 表单数据 - 参照原项目的 form 结构 */
const formData = reactive<MerchantData>({
  id: undefined,
  merchantCode: "",
  merchantName: "",
  merchantType: "",
  merchantLevel: "",
  bankName: "",
  bankAccount: "",
  address: "",
  mobile: "",
  tel: "",
  contactPerson: "",
  email: "",
  remark: "",
});

/** 表单验证规则 - 参照原项目的 rules */
const formRules: FormRules<MerchantData> = {
  merchantCode: [
    { required: true, message: "商户编号不能为空", trigger: "blur" },
    { min: 2, max: 50, message: "商户编号长度在2到50个字符", trigger: "blur" },
  ],
  merchantName: [
    { required: true, message: "商户名称不能为空", trigger: "blur" },
    { min: 2, max: 100, message: "商户名称长度在2到100个字符", trigger: "blur" },
  ],
  merchantType: [
    { required: true, message: "请选择企业类型", trigger: "change" },
  ],
  mobile: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  tel: [
    {
      pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,8}$/,
      message: "请输入正确的座机号码",
      trigger: "blur",
    },
  ],
  email: [
    {
      type: "email",
      message: "请输入正确的邮箱地址",
      trigger: ["blur", "change"],
    },
  ],
};

/** 监听数据变化，初始化表单 */
watch(
  () => props.data,
  (newData) => {
    if (newData && props.visible) {
      nextTick(() => {
        Object.assign(formData, {
          id: newData.id,
          merchantCode: newData.merchantCode || "",
          merchantName: newData.merchantName || "",
          merchantType: newData.merchantType || "",
          merchantLevel: newData.merchantLevel || "",
          bankName: newData.bankName || "",
          bankAccount: newData.bankAccount || "",
          address: newData.address || "",
          mobile: newData.mobile || "",
          tel: newData.tel || "",
          contactPerson: newData.contactPerson || "",
          email: newData.email || "",
          remark: newData.remark || "",
        });
      });
    }
  },
  { immediate: true, deep: true }
);

/** 监听对话框显示状态 */
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      // 对话框打开时，如果是新增模式，重置表单
      if (props.mode === "add") {
        resetForm();
      }
    } else {
      // 对话框关闭时清理验证状态
      nextTick(() => {
        formRef.value?.clearValidate();
      });
    }
  }
);

/** 重置表单 */
function resetForm() {
  Object.assign(formData, {
    id: undefined,
    merchantCode: "",
    merchantName: "",
    merchantType: "",
    merchantLevel: "",
    bankName: "",
    bankAccount: "",
    address: "",
    mobile: "",
    tel: "",
    contactPerson: "",
    email: "",
    remark: "",
  });
  nextTick(() => {
    formRef.value?.clearValidate();
  });
}

/** 取消处理 */
function handleCancel() {
  console.log("[商户对话框] 取消操作");
  emit("update:visible", false);
  emit("cancel");
}

/** 确认处理 */
async function handleConfirm() {
  if (!formRef.value) return;

  try {
    // 表单验证
    const valid = await formRef.value.validate();
    if (!valid) {
      ElMessage.warning("请检查表单数据");
      return;
    }

    submitting.value = true;

    // 构建提交数据
    const submitData: MerchantData = { ...formData };
    
    console.log("[商户对话框] 提交数据:", submitData);

    emit("confirm", submitData);
  } catch (error) {
    console.error("[商户对话框] 表单验证失败:", error);
    ElMessage.error("表单验证失败");
  } finally {
    // 延时重置提交状态，给父组件处理时间
    setTimeout(() => {
      submitting.value = false;
    }, 1000);
  }
}

/** 获取表单数据 - 供父组件调用 */
function getFormData(): MerchantData {
  return { ...formData };
}

/** 设置表单数据 - 供父组件调用 */
function setFormData(data: Partial<MerchantData>) {
  Object.assign(formData, data);
}

/** 验证表单 - 供父组件调用 */
async function validateForm(): Promise<boolean> {
  if (!formRef.value) return false;
  try {
    return await formRef.value.validate();
  } catch {
    return false;
  }
}

/** 暴露方法给父组件 */
defineExpose({
  getFormData,
  setFormData,
  validateForm,
  resetForm,
});
</script>

<style scoped>
.merchant-dialog-content {
  @apply max-h-96 overflow-y-auto;
}

.merchant-form {
  @apply p-4;
}

.merchant-form :deep(.el-form-item__label) {
  @apply text-gray-700 font-medium;
}

.merchant-form :deep(.el-input__wrapper) {
  @apply shadow-sm;
}

.merchant-form :deep(.el-select .el-input__wrapper) {
  @apply shadow-sm;
}

.merchant-form :deep(.el-textarea__inner) {
  @apply shadow-sm;
}

.dialog-footer {
  @apply px-4 py-2;
}

/** 响应式设计 */
@media (max-width: 768px) {
  .merchant-form :deep(.el-col) {
    @apply w-full;
  }
}
</style>
